package com.ecreditpal.audio.platform.tencent;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.util.Base64Util;
import com.ecreditpal.audio.AsrCallback;
import com.ecreditpal.audio.AsrRunner;
import com.ecreditpal.audio.model.AudioSession;
import com.ecreditpal.audio.platform.Config;
import com.ecreditpal.audio.util.BaseUtil;
import com.ecreditpal.audio.util.MyHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author lifeng
 * @version 1.0 on 2018/7/5.
 */
@Slf4j
public class TencentAsr extends AsrRunner {

    private static String appId = "1257035476";
    private static String secretKey = "6Y3OhokZHgBVebT1iNvJXkvzxpkZDgz8";
    private static String secretId = "AKIDvhGeqqlIpAJHCvnt9IFB1f8RaXUE7CRW";

    private static String url = "http://aai.qcloud.com/asr/v1/";
    private static String url2 = "aai.qcloud.com/asr/v1/";

    private TreeMap<String, Object> backup = new TreeMap<>();

    private Config config;


    @Override
    public void init(Config config) {
        this.config = config;

        backup.put("projectid", "1013976");
        backup.put("sub_service_type", "1");
        backup.put("engine_model_type", config.getByteRate().equals(8000) ? "8k_0" : "16k_0");
        backup.put("res_type", "1");
        backup.put("result_text_format", "0");
        backup.put("voice_id", "1234567890abcdef");
        backup.put("seq", "0");
        backup.put("end", "1");
        backup.put("timeout", "10");
        backup.put("source", "0");
        backup.put("secretid", config.getAppSecret());
        backup.put("voice_format", 1);
    }

    @Override
    public void process(byte[] data, AsrCallback asrCallback) {
        TreeMap<String, Object> param = new TreeMap<>();
        for (String s : backup.keySet()) {
            param.put(s, backup.get(s));
        }

        param.put("timestamp", System.currentTimeMillis() / 1000);
        param.put("expired", System.currentTimeMillis() / 1000 + 24 * 60 * 60);
        param.put("nonce", (int) (Math.random() * 10000));

        String finalUrl = createUrl(url, config.getAppId(), param);
        String sign = createSign("POST", url2, config.getAppKey(), config.getAppId(), param);
        Map<String, String> headers = new HashMap<>();

        headers.put("Authorization", sign);

        String result = MyHttpClient.postFile(finalUrl, headers, data);

        result = JSON.parseObject(result).getString("text");

        log.info("tencent asr result:{}", result);
        asrCallback.sendMessage(result);
    }


    public static String createSign(String method, String baseUrl, String secretKey, String appId, Map<String, Object> map) {
        StringBuilder sb = new StringBuilder(method);

        sb.append(baseUrl).append(appId).append("?");

        for (String s : map.keySet()) {
            sb.append(s).append("=").append(map.get(s).toString()).append("&");
        }

        String str = sb.replace(sb.lastIndexOf("&"), sb.length(), "").toString();

        String sign = BaseUtil.sign(str, secretKey, "HmacSHA1", "UTF-8");

        return sign;
    }


    public static String createUrl(String baseUrl, String appId, Map<String, Object> params) {
        StringBuilder sb = new StringBuilder(baseUrl).append(appId).append("?");

        for (String s : params.keySet()) {
            sb.append(s).append("=").append(params.get(s).toString()).append("&");
        }

        return sb.replace(sb.lastIndexOf("&"), sb.length(), "").toString();
    }


    public static void main(String[] args) throws IOException {
//        System.out.println(Math.random() * 10000);

        TencentAsr tencentAsr = new TencentAsr();
        Config config = new Config();
        config.setAppId(appId);
        config.setAppKey(secretKey);
        config.setAppSecret(secretId);
        tencentAsr.init(config);
        InputStream is = new FileInputStream("/Users/lifeng/Desktop/pp3.wav");
        byte[] b = new byte[is.available()];

        is.read(b);

        tencentAsr.process(b,null);
    }


}
